package com.china.api.web.dao.impl;

import java.util.*;

import javax.persistence.*;

import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;

import com.china.api.web.dao.ModelDao;


/**
 * 
 * @Description:实体DAO
 * @author:zhaoxudong
 * @version:v1.0.0
 * @Created:2013年12月16日下午11:51:24
 * @Modified:
 */
public class ModelDaoImpl implements ModelDao {
	
	private static final Logger log = (Logger) LoggerFactory.getLogger(ModelDaoImpl.class);

	@PersistenceContext(unitName = "jpaPU")
	private EntityManager em;

	public List<Class<?>> findAll(Class<?> cla) {
		String jpq = "FROM "+cla.getSimpleName();
		Query query = em.createQuery(jpq);
		return query.getResultList();
	}

	public List<Class<?>> findByCond(Class<?> cla , Map<String, String> map) {
		String jpq = "FROM " + cla.getSimpleName() + " WHERE 1=1 ";
		StringBuffer cond = new StringBuffer();
		Set<String> set = map.keySet();
		for(String key : set)
			cond.append( key + " = '" + map.get(key) + "'");
		Query query = em.createQuery(jpq);
		return query.getResultList();
	}

	public Class<?> findById(Class<?> cla, String id) {
		return (Class<?>) em.find(cla, id);
	}
	
	public void del(Class<?> cla, String id) {
		em.getTransaction().begin();
		Class<?> clzz = (Class<?>) em.find(cla, id);
		em.remove(clzz);
		em.getTransaction().commit();
	}

	public void saveOrUpate(Class<?> cla) {
		em.getTransaction().begin();  
		em.merge(cla);
		em.getTransaction().commit();
	}

}
